<template>
    <div class="catalogue-detail-page">
        <template v-if="loading">
            <van-loading class="loading" color="#1989fa" />
        </template>
        <template v-else>
            <!-- 全屏预览文档 -->
            <div class="catalogue-detail is--fullscreen" v-if="isFullScreen">
                <FileView
                    ref="fileWrapRef"
                    mode="h5"
                    :fileData="courseDetail.materialVO"
                    :detail="courseDetail"
                    :catalogue-id="activeId"
                    :is-buy-person="isBuyPerson"
                    @handle-full-screen="handleFullScreen"/>
            </div>
            
            <!-- 详情页带目录 -->
            <div class="catalogue-detail" v-else>
                <div class="content-player-detail">
                    <template v-if="courseDetail?.contentType === 'material'">
                        <!-- 看视频 -->
                        <VideoCell
                            v-if="isVideo"
                            ref="videoWrapRef"
                            mode="h5"
                            :video-data="courseDetail.materialVO"
                            :detail="courseDetail"
                            :is-buy-person="isBuyPerson"
                            :catalogue-id="activeId"/>
                        <div class="other-file-detail" v-else>
                            <img :src="courseDetail?.materialVO?.snapshotCover || require('@/assets/images/catalogue-icons/file-cover@2x.png')" alt="">
                            <div class="bottom-detail">
                                <div>
                                    <img class="file-type" :src="imgSrc(courseDetail?.materialVO?.materialType)" alt="">
                                    <span class="file-size">{{courseDetail?.materialVO?.materialSizeFormat}}</span>
                                </div>
                                <van-button class="view-btn" @click="handleFullScreen(true)">预览</van-button>
                            </div>
                        </div>
                        <div class="material-title">
                            <span>{{ detailData?.title }}</span>
                        </div>
                    </template>
                    <template v-else-if="courseDetail?.contentType === 'rtf'">
                        <RichText :content="courseDetail.contentExtend" />
                    </template>
                    <template v-else-if="courseDetail?.contentType === 'scene'">
                        <div class="scene-detail"></div>
                    </template>
                    <template v-else-if="courseDetail?.contentType === 'meeting'">
                        <MeetingDetail
                            :meeting-info="courseDetail.meetingVO"
                        />
                    </template>
                </div>
                <template v-if="courseDetail?.contentType !== 'meeting'">
                    <div class="comment-wrapper comment-wrapper-margin-bottom">
                        <CatalogueHorizontal :activeId="activeId" @changeCatalogue="changeCatalogue"/>
                    </div>
                    <div class="comment-wrapper comment-wrapper-margin-bottom">
                        <Comment
                            :is-fullscreen="isFullScreen"
                            :is-creater="isCreater"
                            :is-upload-img="false"
                            :has-comment-popup="true"
                            :catalogue-id="activeId"
                            @play-to-specified-point="playToSpecifiedPoint"
                        />
                    </div>
                </template>
            </div>
        </template>
    </div>
</template>

<script setup>
import FileView from './part/file-view.vue';
import VideoCell from './part/video-cell.vue';
import RichText from '@/components/rich-text';
import MeetingDetail from './detail/meeting-detail';
import Comment from './comment';
import CatalogueHorizontal from './detail/catalogue-horizontal.vue';
import {computed, onMounted, ref} from 'vue';
import {useRoute} from 'vue-router';
import {useStore} from 'vuex';
import {Loading as VanLoading, Button} from 'vant';
import { queryToJson } from '@/lib/tools';
import {isApp} from '@/lib/judge-env.js';
import { handleErrorPage } from '@/lib/tools.js';

const route = useRoute();
const store = useStore();

// const isFullScreen = computed(() => {
//     return courseDetail.value && ['doc', 'xls', 'ppt', 'pdf', 'edit', 'live'].includes(courseDetail.value.tag);
// });

const fileWrapRef = ref(null);

const videoWrapRef = ref(null);

function playToSpecifiedPoint(data) {
    if (videoWrapRef.value) {
        videoWrapRef.value.playToSpecifiedPoint(data.resourceStart);
    }
}

// 页面加载
const loading = ref(false);

// 素材信息
const courseDetail = ref({});

// 当前选中的课件id
const activeId = ref(route.query.catalogueId);

// 素材是否是视频
const isVideo = computed(() => {
    return courseDetail.value && courseDetail.value.tag === 'video';
});

// 是否全屏 文件点击预览会全屏
const isFullScreen = ref(false);

// 点击切换目录
function changeCatalogue (catalogueId) {
    activeId.value = catalogueId;
    if (!isApp()) {
        window.history.replaceState('', '', `?catalogueId=${catalogueId}&courseId=${route.query.courseId}`);
    } else {
        // store.dispatch('jsBridge/disposeBridge', {
        //     method: 'goNewPage',
        //     url: {
        //         name: 'catalogueDetail',
        //         params: {
        //             moocId: route.params.moocId
        //         },
        //         query: { 
        //             courseId: route.query.courseId,
        //             catalogueId: catalogueId
        //         }
        //     },
        //     isReplace: true,
        //     naviBarHidden: false
        // })
    }
    
    
    queryCoursewareContentList(catalogueId);
}

// 获取当前选中的课件的信息
function queryCoursewareContentList() {
    loading.value = true;
    G_transmit('courseContentDetail', {
        queries: {
            id: activeId.value || route.query.catalogueId || ''
        }
    }).then(res => {
        courseDetail.value = res.data || {};
        loading.value = false;
    }).catch((_err) => {
        loading.value = false;
        if (_err.status && _err.status.code && [10000002].includes(_err.status.code)) { // 目录不存在
            handleErrorPage('deleteCatelogue', route.params.moocId);
        } else {
            G_dispatchEvent('toast', { message: _err?.status?.desc || '服务开小差了～', type: 'error'});
        }
    })
}

// 慕课详情
const detailData = ref({});

// 是否是购买者
const isBuyPerson = computed(() => {
    return detailData.value?.isBuy;
})

// 是否是创建者
const isCreater = computed(() => {
    return detailData.value?.isMyCreate;
})

// 获取课程详情
async function getCourseDetail() {
    try {
        let res = await G_transmit('moocDetail', {
            queries: {
                id: route.params.moocId
            },
            silence: true
        })

        detailData.value = res.data || {};

        // 不是购买者 并且不是创建人
        let notCourseUser = !detailData.value?.isBuy && !detailData.value?.isMyCreate;

        let isPublish = detailData.value?.publishState == 1 && detailData.value?.state == 4;

        // 课程未发布 除创建人和已经报名的人都不能看
        if (!isPublish && notCourseUser) {
            handleErrorPage('unpublished', route.params.moocId);
        }
        // 慕课发布了 除创建人和已经报名的人都不能看
        if(notCourseUser) {
            handleErrorPage('notsignup', route.params.moocId);
        }
    } catch(_err) {
        // 禁用课程 30800500 删除课程 30800404
        if (_err.status && _err.status.code && [30800500, 30800404].includes(_err.status.code)) {
            handleErrorPage('delete', route.params.moocId);
        }  else {
            G_dispatchEvent('toast', { message: _err?.status?.desc || '服务开小差了～', type: 'error'});
        }
    }
}

function setTitle() {
    store
        .dispatch('jsBridge/disposeBridge', {
            method: 'setNativeTitle',
            titleInfo: {
                title: '',
                naviBarHidden: false
            }
        });
}

const fileTypes = ['audio', 'doc', 'img', 'pdf', 'ppt', 'video', 'xls', 'catalogue', 'edit', 'live', 'evaluate']
const imgs = {
    'audio': require('@/assets/images/file-icons/audio-icon.png'),
    'doc': require('@/assets/images/file-icons/doc-icon.png'),
    'img': require('@/assets/images/file-icons/img-icon.png'),
    'others': require('@/assets/images/file-icons/others-icon.png'),
    'pdf': require('@/assets/images/file-icons/pdf-icon.png'),
    'ppt': require('@/assets/images/file-icons/ppt-icon.png'),
    'video': require('@/assets/images/file-icons/video-icon.png'),
    'xls': require('@/assets/images/file-icons/xls-icon.png'),
    'catalogue': require('@/assets/images/catalogue-icon.png'),
    'edit': require('@/assets/images/file-icons/doc-icon.png'),
    'live': require('@/assets/images/file-icons/live-icon.png'),
    'evaluate': require('@/assets/images/file-icons/evaluate-icon.png'),
}

function imgSrc(str) {
    return fileTypes.indexOf(str) === -1 ? imgs.others: imgs[str]
}

// 全屏展示文档切换
function handleFullScreen (val) {
    console.log(val, 'hhhhhh');
    isFullScreen.value = val;
}

onMounted(async() => {
    setTitle();
    await getCourseDetail();
    queryCoursewareContentList();
})
</script>

<style lang="scss" scoped>
$safe-area-inset-bottom: 48px;

.catalogue-detail-page {
    height: 100vh;
    background: #FFFFFF;
    font-family: PingFangSC-Regular, PingFang SC, sans-serif;
    font-size: 14px;
    color: #171A1D;

    .loading {
        position: absolute;
        left: 0;
        top: 0;
        height: 100%;
        width: 100%;
        z-index: 9999;
        display: flex;
        justify-content: center;
        align-items: center;
        background: rgba(255, 255, 255, 0.8);
    }

    .catalogue-detail {
        background: #FFF;
        height: 100%;
        display: flex;
        flex-direction: column;

        .content-player-detail {
            flex: none;
            background: #F5F5F5;

            .material-res-player {
                height: 210px;
            }
            .material-title {
                background: #FFFFFF;
                margin-bottom: 6px;
                padding: 15px;
                line-height: 22px;
                font-weight: 600;
                font-size: 14px;
                color: #171A1D;
                word-break: break-all;
            }

            .scene-detail {
                margin-bottom: 6px;
                height: 210px;
                width: 100%;
                background: #FFF url(~@/assets/images/lesson-default.png) no-repeat center;
                background-size: contain;
            }
            .other-file-detail {
                position: relative;
                width: 100%;
                height: 210px;
                img {
                    width: 100%;
                    height: 210px;
                }
                .bottom-detail {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    position: absolute;
                    bottom: 0;
                    width: 100%;
                    height: 44px;
                    padding: 0 15px;
                    background: rgba(0, 0, 0, 0.65);
                    .file-type {
                        width: 21px;
                        height: 24px;
                        vertical-align: middle;
                    }
                    .file-size {
                        margin-left: 6px;
                        font-size: 13px;
                        vertical-align: middle;
                        color: #ffffff;
                    }
                    .view-btn {
                        font-size: 14px;
                        width: 48px;
                        height: 28px;
                        padding: 0;
                        color: #ffffff;
                        background: #0084F6;
                        border-radius: 2px;
                        border: none;
                    }
                }
            }
            
        }
        
        .comment-wrapper {
            flex: 1;
            // overflow-y: auto;
            margin-bottom: 48px;
        }

        &.is--fullscreen {
            .content-player-detail {
                flex: 1;
                background: #FFFFFF;

                .material-res-player {
                    height: 100%;
                }
            }
            // .comment-detail {
            //     flex: none;
            // }
        }
    }
}
</style>